package binarytree;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @Author: 海琳琦
 * @Date: 2021/9/8 17:59
 */
public class Title145 {
    class TreeNode{
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(){}
        TreeNode(int val, TreeNode left, TreeNode right){
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
    static List<Integer> result;
    public static void main(String[] args) {

    }

    /**
     * 后序遍历树
     * @param root
     * @return
     */
    public List<Integer> postorderTraversal(TreeNode root) {
        result = new ArrayList<>();
        TreeNode q = null;
        Stack<TreeNode> stack = new Stack<>();
        while(root!=null||!stack.isEmpty()){
            while(root!=null){
                stack.add(root);
                root = root.left;
            }
            root = stack.peek();
            if(root.right==null||root.right==q){
                result.add(root.val);
                q = root;
                stack.pop();
                root = null;
            }else{
                root = root.right;
            }
        }
        return result;

    }

//    private  void postOrder(TreeNode root){
//        if(root!=null){
//            postOrder(root.left);
//            postOrder(root.right);
//            result.add(root.val);
//        }
//    }

}
